package test;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/lastAccessTime")
public class LastAccessTimeServlet extends HttpServlet{

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 1.记录当前时间，设置到Cookie里面（不管是不是第一次访问，都要记录当前访问时间）
		Date date = new Date();
		System.out.println(date);//Mon Feb 22 11:31:50 CST 2021
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-ddhh:mm:ss");
		String time = simpleDateFormat.format(date);
		Cookie cookie = new Cookie("lastAccessTime", time);
		resp.addCookie(cookie);
		
		// 2. 获取Cookie信息，显示到页面上（第一访问是没有Cookie）
		Cookie[] cookies = req.getCookies();// 如果是第一次拿出来的数组是null
		String lastAccessTime = null;
		if (cookies != null) {
			for (Cookie coo : cookies) {
				if ("lastAccessTime".equals(coo.getName())) {
					lastAccessTime = coo.getValue();
				}
			}
		}
		
		// 3. 显示上一次访问时间
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter printWriter = resp.getWriter();
		if (lastAccessTime == null) {
			printWriter.println("您是第一次访问");
		} else {
			printWriter.println("您上次访问时间：" + lastAccessTime);
		}
		printWriter.close();
		
	}
	
	
	public static void main(String[] args) {
		Date date = new Date();
		System.out.println(date);//Mon Feb 22 11:31:50 CST 2021
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String time = simpleDateFormat.format(date);
		System.out.println(time);// 2021-02-22 11:31:50
	}
		
}
